package com.itplh.modules.shirojwt.controller;

import com.itplh.modules.shirojwt.common.RestResponse;
import com.itplh.modules.shirojwt.common.RestResponse.Builder;
import com.itplh.modules.shirojwt.constants.OAuthConstant.Code;
import com.itplh.modules.shirojwt.pojo.ShiroJwtUser;
import com.itplh.modules.shirojwt.service.ShiroJwtUserService;
import com.itplh.modules.shirojwt.utils.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: tanpeng
 * @Date: 2019-07-10 22:34
 * @Version: V1.0
 */
@RestController
@RequestMapping(value = "/shirojwt")
public class LoginController {

  @Autowired
  private ShiroJwtUserService shiroJwtUserService;


  @PostMapping("/login")
  public RestResponse<String> login(@RequestBody ShiroJwtUser shiroJwtUser) {
    String username = shiroJwtUser.getUsername();
    String password = shiroJwtUser.getPassword();
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
      RestResponse.Builder builder = new Builder();
      builder.setMsg("账号和密码不能为空!");
      builder.setCode(Code.BUSINESS_ERROR);
      return builder.build();
    }
    ShiroJwtUser user = shiroJwtUserService.findByUserName(username);
    if (null == user || !password.equals(user.getPassword())) {
      throw new UnknownAccountException("用户名和密码错误");
    }
    String msg = "登录成功,请妥善保管您的token,有效期5分钟!";
    Map<String, Object> data = new HashMap(3);
    data.put("token", JwtUtils.createToken(username, password));
    data.put("user", user);
    return RestResponse.OK(msg, data);
  }

  @GetMapping(value = "/logout")
  public String logout() {
    return "成功注销！";
  }

}
